package com.zsk.shop.config.aop;

import com.alibaba.fastjson.JSONObject;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.utils.HttpContext;
import com.zsk.shop.common.utils.HttpUtil;
import com.zsk.shop.common.utils.RedisUtil;
import com.zsk.shop.common.utils.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;

@Slf4j
@Aspect
@Component
public class ParamLogger {

    @Pointcut("execution(* com.zsk.shop.controller..*(..))")
    public void controller() {
    }

    @Before("controller()")
    public void controller(JoinPoint point) {
    }

    @Around("controller()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object retVal = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ipBlack = "IpBlack:" + HttpUtil.getIpAddress(request);
        String ip = (String) RedisUtil.get(ipBlack);
        if (ToolUtil.isNotEmpty(ip) && ip.equals(HttpUtil.getIpAddress(request))) {
            //ip在黑名单中返回false
            //return false;
            BaseResponse defaultResponse = new BaseResponse();
            defaultResponse.setCode(-1);
            defaultResponse.setMessage("ip在黑名单中，拒绝访问.");
            log.info("IpBlackAopInterceptor, 当前请求ip" + ip + ",在黑名单中，拒绝访问");
            return defaultResponse;
        }
        String param = null;
        if (ToolUtil.isNotEmpty(request.getParameterMap())) {
            param = JSONObject.toJSONString(request.getParameterMap());
        } else {
//            param = requestJsonParam(request);
        }
        log.info("\n\t请求用户token: {}\n\t请求用户id: {}\n\t请求IP: {}\n\t请求路径: {}\n\t请求参数: {}",
                HttpContext.getToken(), HttpContext.getSafeUserNo(), HttpUtil.getIpAddress(request), request.getRequestURL(), param);
        long startTime = System.currentTimeMillis();
        Object[] args = point.getArgs();
        retVal = point.proceed(args);
        long endTime = System.currentTimeMillis();
        log.info("\n\t执行时间: {} ms \n\t返回值: {}", endTime - startTime, JSONObject.toJSONString(retVal));
        return retVal;
    }

    public static String requestJsonParam(HttpServletRequest request) {
        String param = null;
        try {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            if (ToolUtil.isNotEmpty(responseStrBuilder)) {
                param = responseStrBuilder.toString();
            }
            streamReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }

}
